<template>
  <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
    <el-form-item label="帐号" prop="user">
      <el-input v-model="ruleForm.user" placeholder="帐号/邮箱/手机" label="admin" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" autocomplete="off" placeholder="输入密码">12345</el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import type { FormInstance } from 'element-plus'
import { login } from './api';
import router from '../utils/router';

const ruleFormRef = ref<FormInstance>()


const ruleForm = reactive({
  user: '',
  password: '',
})

const rules = reactive({
  user: [
    { required: true, message: '帐号不能为空', trigger: 'blur' },
    { min: 3, message: '长度不能小于3', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      await login(ruleForm).then((resp)=>{
        console.log(resp.data.data.token);
        window.sessionStorage.setItem('token', resp.data.data.token)
        router.push('/home')
        return true
      })
    } else {
      console.log('error submit!', fields)
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
